//
//  SWTabBar.swift
//  SinaWeibo
//
//  Created by wszyxc on 16/7/18.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

import UIKit


//定义一个协议
protocol SWTabBarDelegate:NSObjectProtocol{
    
    func composeBtnClick()
}

class SWTabBar: UITabBar {
    

    weak var swDelegate :SWTabBarDelegate?
    
    //定义一个闭包,给加号点击时调用
    var closure:(()->())?

    //初始化
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        //设置子控件
        addSubview(composeButton)
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    
    //布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //对子控件进行重新布局
        setupLayout()
      
    }
    
    
    ///设置控件的布局
    func setupLayout(){
    
        let itemW:CGFloat = ScreenWidth/5
        var itemX:CGFloat = 0
        var index = 0
        
        for item in self.subviews{
            
//           if item.isKindOfClass(NSClassFromString(UIBarButton))
            
            if item.isKindOfClass(UIControl.self) {
     
                if !item.isKindOfClass(UIButton.self){
    
                    itemX = itemW * CGFloat(index)
                    index++
                    if index == 2{
                        index++
                    }
                    
                    item.frame.size.width = itemW
                    item.frame.origin.x = itemX
                    
                }else{
                    
                    itemX = itemW * 2
                    item.frame = CGRectMake(itemX, 0, itemW, frame.size.height)
                }

            }
            
            composeButton.center.x = frame.width * 0.5
            composeButton.center.y = frame.height * 0.5
      
        }
        
    }
    
    
 /// 懒加载按钮
    
    lazy var composeButton:UIButton = {
       
        let composeButton = UIButton(type: .Custom)
        
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        
        return composeButton
        
    }()
    
    
    func composeButtonClick(){
        
        
        //点击加号按钮时  执行闭包 将点击事件传递给控制器
        
        //闭包
//        closure?()
        
        //代理:这里用了可选值其实就是执行了OC里面的判断
        
            swDelegate?.composeBtnClick()
        
      
    }
    
    

}
